<template>
  <div
    v-if="noDataFlag"
    class="no-data-wrapper"
  >
    <img
      src="~assets/exam/no-data.png"
      class="pic"
    >
    <h4 class="text">
      暂无数据
    </h4>
  </div>
  <!-- -if="!loading || slickLoaded" -->
  <div
    v-else
    v-show="!loading"
    class="page-view"
    :class="curQuestion.QuestionId !== 0 ? 'question-page' : 'desc-page'"
  >
    <QuestionHeaderH5
      v-if="!isOutLimit"
      :question="curQuestion"
      :index="currentSlide"
      :qlength="question.QuestionList.length"
      @reload="onReload"
      @feedbackCorrection="onSubmitCorrection"
    />

    <div
      v-touch="{swipeleft: swipeLeft, swiperight: swipeRight}"
      class="content"
    >
      <!-- 配伍选择题，综合选择题，综合分析简答题(9)主题干 -->
      <template v-if="!isOutLimit">
        <CooperateMainTitle
          v-if="curQuestion.QuestionId !== 0 && curQuestion.QuestionTypeId === 5"
          :option-list="curQuestion.OptionList"
          :precondition="curQuestion.MainName"
        />
        <SyntheticalMainTitle
          v-if="curQuestion.QuestionId !== 0
            && (curQuestion.QuestionTypeId === 7 || curQuestion.QuestionTypeId === 9
            || curQuestion.QuestionTypeId === 6 || curQuestion.QuestionTypeId === 8)"
          :main-question-content="curQuestion.MainName"
        />
      </template>
      <!-- v-lazy-container="{ selector: 'img:not(.imgNotPreview)' }" -->
      <!-- @edge="onEdge" -->
      <component
        :is="renderMain"
        v-if="question.QuestionList.length"
        :question="curQuestion"
        :should-show-answer="showAnswer"
        :swiper-index="currentSlide"
        :style="{ opacity }"
        class="question-main"
        @nextSwiper="onNextSwiper"
      />
    </div>
    <!-- eslint-disable vue/eqeqeq -->
    <QuestionFooterH5
      v-show="!(curQuestion.QuestionId === 0 && $route.query.showAnswer != 1)"
      :question-info="curQuestion"
      :index="currentSlide"
      :qlength="question.QuestionList.length"
      :show-answer="showAnswer"
      @goTestCard="onGoTestCard"
      @reload="onReload"
      @goNext="swipeLeft"
      @goPrev="swipeRight"
    />
    <AppSwipeTip
      v-if="isFirstShow"
      @hideTip="isFirstShow = false"
    />
  </div>
</template>

<script lang="ts">
import { mapState } from 'vuex'
import { SET_QUESTIONS, SET_USER_INFO } from '@/store/mutations'
import mixins from 'vue-typed-mixins'
import testSubmit, { MappedState } from '@/mixins/testSubmit'
import { HTTP_CODES, syncRequest } from '@/plugins/http.plugin'
import { AppInfo, loading } from '@/lib/appMethods'
import vTouch from '@/directives/vTouch_Hammer'
export default mixins(testSubmit).extend({
  directives: {
    touch: vTouch,
  },
  components: {
    Choose: () => import('components/Exam/Choose.vue'),
    TestTryEnd: () => import('components/Exam/TestTryEnd.vue'),
    Subjective: () => import('components/Exam/SubjectiveQuestion.vue'),
    FillBlanks: () => import('components/Exam/FillBlanksQuestion.vue'),
    AppSwipeTip: () => import('components/Exam/AppSwipeTip.vue'),
    QuestionDesc: () => import('components/Exam/Desc.vue'),
    QuestionHeaderH5: () => import('components/Exam/QuestionHeaderH5.vue'),
    QuestionFooterH5: () => import('components/Exam/QuestionFooterH5.vue'),
    QuestionHeaderApp: () => import('components/Exam/QuestionHeaderApp.vue'),
    QuestionFooterAPP: () => import('components/Exam/QuestionFooterAPP.vue'),
    CooperateMainTitle: () => import('components/Exam/CooperateMainTitle.vue'),
    SyntheticalMainTitle: () => import('components/Exam/SyntheticalMainTitle.vue'),
  },
  data () {
    const isFirstShow = !localStorage.getItem('isTestShowed')
    return {
      tempCurrentSlide: 0,
      currentSlide: 0,
      progress: 0,
      showAnswer: false,
      search: '',
      noDataFlag: false,
      loading: false,
      toastInst: null as any,
      slickLoaded: false,
      opacity: 1,
      isFirstShow: AppInfo.isApp && isFirstShow,
      isFromAPP: AppInfo.isApp,
      backCount: 0,
      // question: {
      //   QuestionList: [],
      //   PaperName: '',
      //   LastQuestionId: 0,
      //   QuestionTotalCount: 0,
      //   RightCount: 0,
      // } as any as QuestionInfo,
    }
  },
  computed: {
    ...mapState(['question']) as MappedState,
    curQuestion (): any {
      return this.question.QuestionList[this.currentSlide || 0] || {}
    },
    renderMain (): string {
      if (this.isOutLimit) {
        if (AppInfo.isApp) {
          AppInfo.callMethod('reLogin', '', true).then((userData: any) => {
            this.$store.commit(SET_USER_INFO, userData)
          })
          return ''
        }
        return 'TestTryEnd'
      }
      if (this.curQuestion.QuestionId === 0) {
        return 'QuestionDesc'
      }
      // if (this.curQuestion.QuestionTypeId === 8) {
      //   return 'FillBlanks'
      // }
      if (this.curQuestion.QuestionTypeId === 8 || this.curQuestion.QuestionTypeId === 9) {
        return 'Subjective'
      }
      return 'Choose'
    },
    isOutLimit () {
      return false
    },
    questionList (): any[] {
      return this.question.QuestionList
    },
    // toShowQuestions (): any[] {
    //   return this.question.QuestionList.slice(this.virtualData.from, this.virtualData.to + 1)
    // },
  },
  activated () {
    const { ShowType, Type, doAgain, showAnswer } = this.$route.query
    /* eslint-disable eqeqeq */
    // const shouldShowAnswer = Type == '3' || ShowType == '1' || ShowType == '2'
    /* eslint-disable eqeqeq */
    const shouldShowAnswer = ShowType == '1' || ShowType == '2'
    const isAnswerShow = showAnswer && showAnswer != '0'
    this.showAnswer = isAnswerShow || shouldShowAnswer
    this.backCount = 0
    // this.loading = true

    this.fetchData()
    // if (location.search !== this.search) {
    //   this.search = location.search
    //   this.fetchData()
    // }
    if (window.questionIndex !== -1) {
      const toShowSlide = window.questionIndex || 0
      this.tempCurrentSlide = toShowSlide
      this.currentSlide = toShowSlide
      if (window.questionIndex) {
        delete window.questionIndex
      }
      setTimeout(() => {
        window.scrollTo(0, 0)
      })
    }
  },
  beforeRouteLeave (to, from, next) {
    if (this.backCount) {
      next()
      return
    }
    if (to.name !== 'examCard' && to.name !== 'examResult') {
      next(false)
      window.questionIndex = 0
      this.onBeforeLeave().then(res => {
        this.backCount = 1
        this.$router.back()
      }, (e: any) => {
        // 错误为rejected的时候不返回
        if (e === 'rejected') {
          this.backCount = 0
        } else {
          this.backCount = 1
        }
      })
    } else {
      next()
    }
  },
  // mounted () {
  //   window.onunload = this.syncSubmitResult
  // },
  methods: {
    // doAgain：是否重新做题
    // CourseId： 课程id
    // PaperId： 考试iD
    // QuestionType： 筛选 0.全部类型 1.单选，2.多选，3.判断，4.不定项，5.主观题 6.配伍选择题 7.综合分析选择题 8.填空题 9.综合分析简答题
    // 10 摘要型选择题 11.案例分析选择题
    // QuestionTypeCode类型  1.单选，2.多选，3.判断，4.填空 5配伍 6案例分析选择题 7综合分析选择题 8主观题 9综合分析简答题
    // ShowType： 0：所有题目；1：收藏的题目；2：做错的题目。
    // Type 筛选考试类型 0: 错题 1：模拟考试，2：历年真题，3.章节练习，4 每日一练
    // showAnswer：0不显示解析，1显示解析
    // HistoryId

    fetchData () {
      const { PaperId, Type, CourseId,
        PaperTestHistoryId, ShowType, ClassId } = this.$route.query as any
      if (Type == 4 && (!PaperId || PaperId == '0')) {
        this.noDataFlag = true
        AppInfo.callMethod('hideLoading')
        return Promise.resolve()
      }
      this.noDataFlag = false
      this.loading = true
      let url = 'ytjysite/TPaper/GetModelDetail'
      if (this.showAnswer) {
        url = 'ytjysite/EStudy/GetDonePaperDetail'
      }
      return this.$axios({
        url,
        data: {
          PaperId,
          Type,
          // CourseId,
          PaperTestHistoryId,
          ShowType,
          ClassId,
          QuestionType: 0,
        },
        // method: 'get',
      }).then(res => {
        console.log('question', res)
        this.loading = false
        if (res.Items.length === 0) {
          this.noDataFlag = true
        } else {
          this.noDataFlag = false
          const questionList: any[] = []
          let Sequence = 1;
          (res.Items as any[]).forEach(typeList => {
            const { Items, ...oth } = typeList
            Items.forEach((question: any) => {
              questionList.push({
                ...question,
                ...oth,
                Sequence,
                QuestionTypeId: +oth.QuestionTypeCode,
                UserAnswer: question.ChoosedOptionId || [],
                OptionList: question.Items,
              })
              Sequence++
            })
          })
          this.$store.commit(SET_QUESTIONS, {
            QuestionList: questionList,
            PaperTestHistoryId: res.PaperTestHistoryId,
            PaperName: res.Name,
          })

          console.log(questionList)
          if (res.MaxQuestionSeq) {
            this.$toast('已读取上次保存的练习，请继续作答')
          }
          this.tempCurrentSlide = res.MaxQuestionSeq || 0
          this.currentSlide = res.MaxQuestionSeq || 0
        }
      }, e => {
        this.loading = false
        this.$toast(e.message)
        if (e.ResultCode === HTTP_CODES.tokenExpired) {
          AppInfo.callMethod('reLogin', '', true).then((userData: any) => {
            this.$store.commit(SET_USER_INFO, userData)
            this.fetchData()
          })
        }
      })
    },
    whetherScrollTop (toNext: boolean) {
      if (this.curQuestion.QuestionTypeId !== 5 && this.curQuestion.QuestionTypeId !== 7) {
        return true
      }
      if (toNext && !this.curQuestion.IsSameQuestion) {
        return true
      }
      if (!toNext && !this.question.QuestionList[this.currentSlide + 1].IsSameQuestion) {
        return true
      }
      return false
    },
    scrollTop (toNext = true) {
      this.$nextTick(() => {
        if (this.whetherScrollTop(toNext)) {
          // window.scrollTo(0, 0)
          this.$el.scrollTo(0, 0)
          // const appEl = document.getElementById('app') as HTMLDivElement
          // appEl.scrollTo(0, 0)
        }
      })
    },
    // 下一题
    swipeLeft (e?: any) {
      if (this.isOutLimit) {
        return
      }
      if (this.tempCurrentSlide < this.question.QuestionList.length - 1) {
        this.opacity = 0
        this.tempCurrentSlide++
        setTimeout(() => {
          this.currentSlide++
          this.scrollTop()
          this.opacity = 1
        }, 300)
      }
    },
    // 上一题
    swipeRight (e?: any) {
      if (this.isOutLimit && this.currentSlide !==
      this.$store.state.instInfo.TryQuestionCount - (this.question.RightCount || 0)) {
        return
      }
      if (this.tempCurrentSlide > 0) {
        this.opacity = 0
        this.tempCurrentSlide--
        setTimeout(() => {
          this.currentSlide--
          this.scrollTop(false)
          this.opacity = 1
        }, 300)
      }
    },
    onReload (index: number) {
      if (index === this.question.QuestionList.length - 1) {
        index--
      }
      this.tempCurrentSlide = index
      this.currentSlide = index
    },
    onBeforeLeave () {
      const { PaperId, ShowType, fromResult } = this.$route.query
      if (window.submitedPaperId == PaperId || this.noDataFlag ||
        ShowType == '1' || ShowType == '2' || fromResult) {
        delete window.submitedPaperId
        return Promise.resolve('')
      }
      window.onunload = null
      return this.$dialog.confirm({
        message: '确定要退出，并保存本次练习？',
      }).then(() => {
        return this.submitResult(false)
      }, () => {
        // eslint-disable-next-line no-throw-literal
        throw 'rejected'
      })
    },
    onGoTestCard () {
      window.questionIndex = -1
      const { fromApp, ...othQuery } = this.$route.query
      this.$router.push({ name: 'examCard',
        query: {
          ...othQuery,
          showAnswer: this.showAnswer ? '1' : '',
        },
      })
    },
    onNextSwiper () {
      this.swipeLeft()
    },

    // 点击跳转试题纠错页面
    onSubmitCorrection () {
      window.questionIndex = -1
      this.$router.push({
        name: 'questionCorrective',
        query: {
          questionId: this.curQuestion.QuestionId,
          questionTypeDesc: this.curQuestion.QuestionTypeName,
        },
      })
    },

    // 点击预览图片
  },
})
</script>

<style lang="scss" scoped>
$wrapperHeight: 100vh;
.page-view {
  // height: $wrapperHeight;
  background: #fff;
  // /deep/ .has-header & {
  //   background: #f2f3f8;
  // }
}
.no-data-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  height: calc(#{$wrapperHeight} - #{$navBarHeight * 2});
  font-size: 30px;
  .pic {
    width: 200px;
  }
  .text {
    margin-top: 30px;
    color: #999;
  }
  .van-loading--white {
    border-radius: 4px;
    background-color: rgba(0, 0, 0, 0.5);
    padding: 10px;
  }
}
.loading-wrapper {
  position: fixed;
  z-index: 100;
}
.content {
  display: flex;
  flex-direction: column;
  padding-top: $examHeaderInH5;
  // min-height: calc(#{$wrapperHeight} - #{$examHeaderInH5});
  min-height: 100vh;
  user-select: none;
  /deep/ {
    .slick-initialized {
      width: 100%;
      flex: 1;
    }
    .has-header & {
      // padding-top: $examHeaderInH5;
      min-height: calc(100vh - #{$navBarHeight});
    }
    // .swiper-wrapper {
    //   height: 100%;
    // }
    // .swiper-slide, .swiper-wrapper {
    //   min-height: 100%;
    // }
    // img {
    //   height: 340px;
    // }
    // img[lazy="loaded"]
    img[lazy=error] {
      display: none;
    }
  }
}
.question-main {
  transition: opacity 300ms;
}
// .desc-page {
//   /deep/ .swiper-slide {
//     height: calc(#{$wrapperHeight} - #{$examHeaderInH5});
//   }
// }
.question-page {
  // /deep/ .swiper-slide {
  //   min-height: calc(#{$wrapperHeight} - #{$examHeaderInH5 + $examFooterInH5});
  // }
  .content {
    padding-bottom: $examFooterInH5;
  }
}
// .static-content {

// }
</style>
